package cn.btks.databasehandler.handle.service.impl;

import cn.btks.commonserver.pojo.PageList;
import cn.btks.commonserver.result.ResultState;
import cn.btks.commonserver.result.StateInfo;
import cn.btks.databasehandler.handle.pojo.BackUpConfig;
import cn.btks.databasehandler.handle.pojo.BackUpResult;
import cn.btks.databasehandler.handle.repository.BackUpConfigRepository;
import cn.btks.databasehandler.handle.repository.BackUpResultRepository;
import cn.btks.databasehandler.handle.service.BackUpResultService;
import cn.btks.databasehandler.handle.util.QuartzUtil;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.*;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @Author lijun
 * @Date 2020/12/28 12:08
 */
@Service
@Transactional
public class BackUpResultServiceImpl implements BackUpResultService {

    @Autowired
    BackUpResultRepository backUpResultRepository;

    @Autowired
    BackUpConfigRepository backUpConfigRepository;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driver;

    @Override
    public ResultState findPagesByConfigNameAndConfigModeAndConfigCycle(Integer page, Integer pageSize, String configName, Integer configMode, Integer configCycle) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Specification<BackUpResult> specification = new Specification<BackUpResult>() {
            @Override
            public Predicate toPredicate(Root<BackUpResult> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (!StringUtils.isEmpty(configName)) {
                    predicates.add(criteriaBuilder.like(root.get("configName"),
                            "%" + configName + "%"));
                }
                if (configMode != null) {
                    predicates.add(criteriaBuilder.equal(root.get("backUpMode"),configMode));
                }
                if (configCycle != null) {
                    predicates.add(criteriaBuilder.equal(root.get("backUpCycle"),
                            configCycle));
                }
                criteriaQuery.orderBy(criteriaBuilder.desc(root.get("handleDateTime")));
                Predicate[] predicates1 = new Predicate[predicates.size()];
                return criteriaBuilder.and(predicates.toArray(predicates1));
            }
        };
        Page<BackUpResult> configPage = backUpResultRepository.findAll(specification, pageRequest);
        if(configPage.getTotalElements() > 0){
            PageList pageList = new PageList();
//            List<BackUpResult> backUpResults = new ArrayList<>();
//            List<BackUpConfig> backUpConfigList = configPage.getContent();
//            if(backUpConfigList != null && backUpConfigList.size() > 0){
//                for(BackUpConfig item : backUpConfigList){
//                    List<BackUpResult> backUpResults1 = backUpResultRepository.findAllByConfigId(item.getId());
//                    if(backUpResults1 != null && backUpResults1.size() >0){
//                        backUpResults.addAll(backUpResults1);
//                    }
//                }
//            }
            pageList.setResult(configPage.getContent());
            pageList.setPageNum(configPage.getTotalPages());
            pageList.setTotalCount(configPage.getTotalElements());
            return new ResultState(StateInfo.FIND_OK.getCode(), StateInfo.FIND_OK.getMsg(), pageList);
        }
        return new ResultState(StateInfo.FIND_NULL.getCode(), StateInfo.FIND_NULL.getMsg());
    }

    @Override
    public ResultState save(BackUpResult backUpResult) {
        if(backUpResult != null && backUpResult.getId() == null){
            BackUpResult backUpResult1 = backUpResultRepository.save(backUpResult);
            return backUpResult1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), backUpResult1) :
                    new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState update(BackUpResult backUpResult) {
        if(backUpResult.getId() != null){
            Optional<BackUpResult> optional = backUpResultRepository.findById(backUpResult.getId());
            if(optional.isPresent()){
                BackUpResult backUpResult1 = backUpResultRepository.save(backUpResult);
                return backUpResult1 != null ? new ResultState(StateInfo.SAVE_OK.getCode(), StateInfo.SAVE_OK.getMsg(), backUpResult1) :
                        new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
            }
        }
        return new ResultState(StateInfo.SAVE_ERROR.getCode(), StateInfo.SAVE_ERROR.getMsg());
    }

    @Override
    public ResultState resumeConfig(Long backUpResultId) throws SQLException {
        Optional<BackUpResult> optional = backUpResultRepository.findById(backUpResultId);
        if(optional.isPresent()){
            Long configId = optional.get().getConfigId();
            String filePath = optional.get().getFilePath();
            boolean result = resume(configId, filePath);
            if(result){
                return new ResultState(StateInfo.START_RESUME_OK.getCode(), StateInfo.START_RESUME_OK.getMsg());
            }
        }
        return new ResultState(StateInfo.START_ERROR.getCode(), StateInfo.START_ERROR.getMsg());
    }

    @Override
    public ResultState delete(Long id) {
        Optional<BackUpResult> optional = backUpResultRepository.findById(id);
        if(optional.isPresent()){
            int result = backUpResultRepository.deleteResultById(id);
            return result > 0 ? new ResultState(StateInfo.DELETE_OK.getCode(), StateInfo.DELETE_OK.getMsg(), result) :
                    new ResultState(StateInfo.DELETE_ERROR.getCode(), StateInfo.DELETE_ERROR.getMsg());
        }
        return new ResultState(StateInfo.DELETE_ERROR_2.getCode(), StateInfo.DELETE_ERROR_2.getMsg());
    }

    private boolean resume(Long id,String filePath) throws SQLException {
        String filepathName = filePath.substring(0, filePath.lastIndexOf("."));
        String outputPath = filepathName + ".out";
        File file = new File(filePath);
        if (file.exists()) {
            try {
                String mysqlBaseDir = QuartzUtil.getBaseDir(url, username, password);
                Optional<BackUpConfig> optional = backUpConfigRepository.findById(id);
                if (optional.isPresent()) {
                    BackUpConfig backUpConfig = optional.get();
                    String url = this.url;
                    String dataBase = backUpConfig.getSelectDBName();
                    switch (dataBase){
                        case "sxydresult":
                            url = "jdbc:mysql://localhost:3306/sxydresult?characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true";
                            break;
                        case "sxyddbhandle":
                            url = "jdbc:mysql://localhost:3306/sxyddbhandle?characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true";
                            break;
                        case "sxydmanage":
                            url = "jdbc:mysql://localhost:3306/sxydmanage?characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true";
                            break;
                    }
                    SQLExec sqlExec = new SQLExec();
                    //设置数据库参数
                    sqlExec.setDriver(driver);
                    sqlExec.setUrl(url);
                    sqlExec.setUserid(username);
                    sqlExec.setPassword(password);
                    //设置字符编码
                    sqlExec.setEncoding("UTF-8");
                    //要执行的脚本
                    sqlExec.setSrc(file);

                    //有出错的语句该如何处理
                    sqlExec.setOnerror((SQLExec.OnError) (EnumeratedAttribute.getInstance(
                            SQLExec.OnError.class, "abort")));
                    sqlExec.setPrint(true); //设置是否输出
                    //输出到文件 sql.out 中；不设置该属性，默认输出到控制台
                    sqlExec.setOutput(new File(outputPath));
                    sqlExec.setProject(new Project()); // 要指定这个属性，不然会出错
                    sqlExec.execute();
                }
                return true;
            } catch (Exception e) {
                return false;
            }
        }
        return false;
    }
}
